package org.shilong.UI.login;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.shilong.MContext.Json.JSonContext;
import org.shilong.MContext.Login.LoginContext;
import org.shilong.MContext.WebRequest.WebRequestContext;
import org.shilong.Model.BusinessCardModel;
import org.shilong.Model.UserInfoModel;
import org.shilong.UI.R;
import org.shilong.UI.TotalMainFrame;
import org.shilong.UI.Test.TestModelFrame;
import org.shilong.UI.profile.MyProfileFrame;
import org.shilong.UI.register.RegisterFrame;
import org.shilong.Utility.IntentUtility;
import org.shilong.Utility.ProgressDialogUtility;
import org.shilong.Utility.SharedPreferenceUtility;
import org.shilong.Utility.ToastUtility;
import org.shilong.Utility.constants.WeiboConstants;

import com.weibo.net.AccessToken;
import com.weibo.net.Oauth2AccessTokenHeader;
import com.weibo.net.Utility;
import com.weibo.net.Weibo;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class LoginFrame extends Activity implements OnClickListener {

	private EditText loginAccountNameEditText, loginAccountPwdEditText;

	private Button loginButton, registerButton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_login_content);

		initViews();

		registerEvents();

	}

	/**
	 * 初始化控件
	 */
	private void initViews() {

		loginAccountNameEditText = (EditText) findViewById(R.id.login_input_account_name);

		loginAccountPwdEditText = (EditText) findViewById(R.id.login_input_account_pwd);

		loginButton = (Button) findViewById(R.id.to_login__button);

		registerButton = (Button) findViewById(R.id.to_register__button);
	}

	private void registerEvents() {

		loginButton.setOnClickListener(this);

		registerButton.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.to_login__button:

			// 登录
			login_logic();

			break;
		case R.id.to_register__button:

			// 注册
			register_logic();

			break;
		default:
			break;
		}

	}

	private String ac_name;
	private String ac_pwd;

	public void login_logic() {

		ac_name = null;
		ac_pwd = null;

		ac_name = loginAccountNameEditText.getText().toString();
		ac_pwd = loginAccountPwdEditText.getText().toString();

		System.out.println("ac_name:" + ac_name);
		System.out.println("ac_pwd:" + ac_pwd);
		if (TextUtils.isEmpty(ac_name)) {

			ToastUtility.showToast(this, "输入用户名");

		} else if (TextUtils.isEmpty(ac_pwd)) {

			ToastUtility.showToast(this, "输入密码");
		} else {

			new LoginTask(LoginFrame.this).execute(ac_name, ac_pwd);

		}

	}

	private class LoginTask extends AsyncTask<String, String, String> {

		private Context mContext;

		public LoginTask(Context con) {

			this.mContext = con;

		}

		@SuppressWarnings("unchecked")
		@Override
		protected void onPostExecute(String result) {

			if (result.equals("no_this_account")) {

				ProgressDialogUtility.cancelDialog();

				ToastUtility.showToast(mContext, "用户名或密码错误!");

			} else {

				/* 获取用户信息并存储到Sharedpreference中 */
				List<UserInfoModel> mList = (List<UserInfoModel>) JSonContext
						.createInstance(JSonContext.TYPE_GET_USER_INFO)
						.getJsonRlt(result);

				UserInfoModel model = mList.get(0);

				System.out.println("List:" + model.toString());

				SharedPreferenceUtility
						.saveAccessTokenAndExpiresToSharedPreference(
								model.getAccess_token(), model.getExpires_in(),
								model.getAccount_name(), model.getUid(),
								LoginFrame.this);

				String[] arr = SharedPreferenceUtility
						.getPersonInfoFromSharedPreference(LoginFrame.this);
				
				
				/**
				 * 封装微博类
				 */
				
				Utility.setAuthorization( new  Oauth2AccessTokenHeader() );
				
				AccessToken token = new AccessToken( arr[0], WeiboConstants.APISECRET );
				token.setExpiresIn( arr[1] );
				
				Weibo.getInstance().setAccessToken(token);
				
			
				/* 获取名片信息 */
				String rlt2 = "nodatas";

				rlt2 = WebRequestContext.createInstance(
						WebRequestContext.TYPE_QUERY_BUSINESS_CARD)
						.getWebRequestRlt(arr[2]);

				System.out.println( "名片信息是：" + rlt2 );
				List<BusinessCardModel> llTwo = new ArrayList<BusinessCardModel>();

				llTwo = (LinkedList<BusinessCardModel>) JSonContext
						.createInstance(JSonContext.TYPE_GET_BUSINESS_CARD)
						.getJsonRlt(rlt2);

				MyProfileFrame.showBusinessCardList = llTwo;

			
				ProgressDialogUtility.cancelDialog();

				ToastUtility.showToast(mContext, "登录成功");

				IntentUtility.goNextFrame(mContext, TotalMainFrame.class, null);

				LoginFrame.this.finish();

			}

		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub

			ProgressDialogUtility.showDialog(mContext, "登录中..");
		}

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub

			String result = "no_this_account";

			String rlt = "";

			rlt = WebRequestContext
					.createInstance(WebRequestContext.TYPE_LOGIN)
					.getWebRequestRlt(params[0], params[1]);

			System.out.println("rlt:" + rlt);

			// 如果是login_right则获取用户信息
			if (rlt.equals("login_right")) {

				result = (String) LoginContext.createInstance(
						LoginContext.TYPE_TO_LOGIN_GET_USER_INFO).getRlt(
						params[0]);
			}

			return result;
		}

	}

	/**
	 * 注册逻辑
	 */
	private void register_logic() {

		IntentUtility.goNextFrame(this, RegisterFrame.class, null);
	}

}
